<template>
  <div class="backup-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据库备份</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 数据库连接选择 -->
      <div class="connection-select">
        <el-select v-model="selectedConnection" placeholder="请选择数据库连接" @change="handleConnectionChange">
          <el-option
            v-for="item in connectionList"
            :key="item.id"
            :label="item.sqlName"
            :value="item.id"
            :disabled="item.status !== 1"
          >
            <span>{{ item.sqlName }}</span>
            <span class="connection-info">
              ({{ item.username }}@{{ item.ip }}:{{ item.port }})
            </span>
          </el-option>
        </el-select>
        <el-button type="primary" :disabled="!selectedConnection" @click="handleBackup">
          <el-icon><Download /></el-icon>开始备份
        </el-button>
      </div>

      <!-- 备份记录表格 -->
      <el-table :data="backupList" style="width: 100%; margin-top: 20px" v-loading="loading">
        <el-table-column prop="id" label="备份ID" width="100" />
        <el-table-column prop="operatorId" label="操作人ID" width="100" />
        <el-table-column prop="operatorName" label="操作人用户名" width="120" />
        <el-table-column prop="connectionId" label="数据库id" width="100" />
        <el-table-column prop="operatorName" label="操作人" width="120" />
        <el-table-column prop="path" label="备份路径" min-width="200" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Refresh, Download } from '@element-plus/icons-vue'

const loading = ref(false)
const selectedConnection = ref(null)
const connectionList = ref([])
const backupList = ref([])

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  totalPage: 0
})

// 获取连接列表
const fetchConnectionList = async () => {
  try {
    const response = await axios.get('/api/connection/list')
    if (response.data.code === '200') {
      connectionList.value = response.data.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取连接列表失败')
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
    ElMessage.error('获取连接列表失败')
  }
}

// 获取备份记录
const fetchBackupList = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/backup/list', {
      params: {
        current: pagination.current,
        size: pagination.size
      }
    })
    if (response.data.code === '200') { 
      const { total, totalPages, data } = response.data.data
      pagination.total = total || 0
      pagination.totalPage = totalPages || 0
      backupList.value = data || []
    } else {
      ElMessage.error(response.data.message || '获取备份记录失败')
    }
  } catch (error) {
    console.error('获取备份记录失败:', error)
    ElMessage.error('获取备份记录失败')
  } finally {
    loading.value = false
  }
}

// 处理备份
const handleBackup = async () => {
  if (!selectedConnection.value) {
    ElMessage.warning('请选择数据库连接')
    return
  }

  try {
    loading.value = true
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const response = await axios.get(
      `/api/connection/${selectedConnection.value}/${userInfo.username}/backup`
    )

    if (response.data.code === '200') {
      ElMessage.success('备份成功')
      fetchBackupList() // 刷新备份记录
    } else {
      ElMessage.error(response.data.message || '备份失败')
    }
  } catch (error) {
    console.error('备份失败:', error)
    ElMessage.error(error.response?.data?.message || '备份失败')
  } finally {
    loading.value = false
  }
}

// 处理连接变更
const handleConnectionChange = () => {
  // 可以在这里添加连接变更时的逻辑
}

// 处理刷新
const handleRefresh = () => {
  fetchBackupList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  fetchBackupList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.current = val
  fetchBackupList()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  fetchConnectionList()
  fetchBackupList()
})
</script>

<style scoped>
.backup-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.connection-select {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 20px;
}

.connection-info {
  color: #909399;
  margin-left: 8px;
  font-size: 12px;
}

:deep(.el-select) {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 